<template>
  <view>
    <view class="status" :style="{ opacity: afterHeaderOpacity }"></view>
    <view class="header">
      <!-- 头部-默认显示 -->
      <view
        class="before"
        :style="{ opacity: 1 - afterHeaderOpacity, zIndex: beforeHeaderzIndex }"
      >
        <view class="back">
          <view class="icon xiangqian" @tap="back" v-if="showBack"></view>
        </view>
        <view class="middle"> 定制商品 </view>
      </view>
    </view>
    <!-- 占位 -->
    <view class="place"></view>
    <!-- 底部菜单 -->
    <view class="footer">
      <view class="icons">
        <button class="box uni-button-box" open-type="share" @tap="shareTo">
          <view class="icon fenxiang"></view>
          <view class="text">分享</view>
        </button>
      </view>
      <view class="btn">
        <view class="buy" @tap="submit">提交</view>
      </view>
    </view>
    <!-- share弹窗 -->
    <view
      class="share"
      :class="shareClass"
      @touchmove.stop.prevent="discard"
      @tap="hideShare"
    >
      <view class="mask"></view>
      <view class="layer" @tap.stop="discard">
        <view class="h1">分享</view>
        <view class="list">
          <button
            class="box"
            open-type="share"
            v-for="item in shareList"
            :key="item.index"
            @tap="shareTo(item)"
          >
            <image :src="item.src" style="margin-top: 20upx"></image>
            <view class="title">
              {{ item.point }}
            </view>
          </button>
        </view>
        <view class="btn" @tap="hideShare"> 取消 </view>
      </view>
    </view>
    <view class="goods-info">
      <view class="title"> 请输入您的商品需求： </view>
      <view class="textarea-box">
        <textarea v-model="textValue" placeholder="请输入内容" />
      </view>

      <!-- 图片上传区域 -->
      <view class="image-upload-section">
        <view class="title"> 上传商品图片（可选）： </view>
        <view class="image-upload-box">
          <view class="uploaded-images" v-if="uploadedImages.length > 0">
            <view
              class="image-item"
              v-for="(image, index) in uploadedImages"
              :key="index"
            >
              <image
                :src="BASE_URL + image.url"
                @tap="previewImage(image.url)"
              />
              <view class="delete-btn" @tap="deleteImage(index)">
                <text class="icon">×</text>
              </view>
            </view>
          </view>

          <view
            class="upload-btn"
            @tap="chooseImages"
            v-if="uploadedImages.length < 5"
          >
            <view class="icon">+</view>
            <view class="text">选择图片</view>
            <view class="tip">最多5张</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { addSelfProduct } from "@/common/api/product.js";
import { BASE_URL } from "@/common/utils/request.js";

export default {
  data() {
    return {
      BASE_URL,
      textValue: "",
      uploadedImages: [], // 已上传的图片列表
      isUploading: false, // 是否正在上传
      //控制渐变标题栏的参数
      beforeHeaderzIndex: 11, //层级
      afterHeaderzIndex: 10, //层级
      beforeHeaderOpacity: 1, //不透明度
      afterHeaderOpacity: 0, //不透明度
      //是否显示返回按钮
      // #ifndef MP
      showBack: true,
      // #endif
      //轮播主图数据
      swiperList: [],
      //轮播图下标
      currentSwiper: 0,
      anchorlist: [], //导航条锚点
      selectAnchor: 0, //选中锚点
      serviceClass: "", //服务弹窗css类，控制开关动画
      specClass: "", //规格弹窗css类，控制开关动画
      shareClass: "", //分享弹窗css类，控制开关动画
      // 商品信息
      goodsData: {},
      selectSpec: null, //选中规格
      shareList: [
        {
          index: "0",
          src: "../../static/img/share/wx.png",
          point: "微信好友",
        },
        {
          index: "1",
          src: "../../static/img/share/pyq.png",
          point: "朋友圈",
        },
      ],
      customerId: "",
    };
  },
  onLoad(option) {
    // #ifdef MP
    //小程序隐藏返回按钮
    // this.showBack = false;
    // #endif
    //option为object类型，会序列化上个页面传递的参数
    // uni.showLoading({
    // 	title: "加载中...",
    // });
    this.customerId =
      uni.getStorageSync("userInfo").id ||
      "66ada023-41eb-4ec3-bc21-0a77f389612b";
  },
  onReady() {},
  mounted() {},
  methods: {
    async submit() {
      const customerId = (uni.getStorageSync("userInfo") || {}).id;
      if (!customerId) {
        uni.showToast({ title: "请先登录", icon: "none" });
        uni.navigateTo({ url: "../login/pre-login" });
        return;
      }

      // 先处理订阅消息（必须在用户点击事件中直接调用）
      this.subscribeMessage();
    },
    // 订阅消息
    subscribeMessage() {
      const tmplId = "LkEglcQu2ATkNSFg7EiHw-ptzCSHsVZ0-A1jksfcubw";
      uni.getSetting({
        withSubscriptions: true,
        success: (settingRes) => {
          // 获取长期订阅的
          if (
            settingRes.subscriptionsSetting?.itemSettings?.[tmplId] === "accept"
          ) {
            // 已订阅，直接执行提交
            this.addSelfProductFun();
          } else {
            uni.requestSubscribeMessage({
              tmplIds: [tmplId],
              success: (res) => {
                if (res[tmplId] === "accept") {
                  // 用户同意订阅，执行提交
                  uni.showToast({ title: "订阅成功" });
                  this.addSelfProductFun();
                } else {
                  // 用户拒绝订阅
                  uni.showModal({
                    title: "消息通知",
                    content:
                      "开启消息通知可以及时了解您的定制商品处理进度，确定要放弃吗？",
                    confirmText: "重新订阅",
                    cancelText: "继续提交",
                    success: (modalRes) => {
                      if (modalRes.confirm) {
                        uni.requestSubscribeMessage({
                          tmplIds: [tmplId],
                          success: (res) => {
                            if (res[tmplId] === "accept") {
                              uni.showToast({ title: "订阅成功" });
                              this.addSelfProductFun();
                            }
                          },
                        });
                      } else {
                        this.addSelfProductFun();
                      }
                    },
                  });
                }
              },
              fail: (err) => {
                console.log(err);
                uni.showToast({
                  title: "订阅失败，但可以继续提交",
                  icon: "none",
                });
                // 订阅失败仍可继续提交
                this.addSelfProductFun();
              },
            });
          }
        },
      });
    },
    shareTo() {
      uni.share({
        provider: "weixin",
        scene: "WXSceneSession",
        type: 4,
        title: this.pName,
        summary: this.pName + ":" + this.pIntroduce,
        success: function (res) {},
        fail: function (err) {},
      });
    },
    addSelfProductFun() {
      uni.showLoading({
        title: "正在提交...",
        mask: true,
      });
      // 生成图片URL字符串，多个URL用逗号分隔
      const imageUrls = this.uploadedImages.map((img) => img.url).join(",");

      const params = {
        productDescription: this.textValue,
        productImage: imageUrls,
        customerId: this.customerId,
      };
      return addSelfProduct(params).then((res) => {
        uni.hideLoading();
        if (res.data.ok) {
          uni.showModal({
            title: "提交成功",
            content:
              res.data.message || "您的定制需求已提交，我们会尽快为您处理",
            showCancel: false,
            confirmText: "知道了",
            success: () => {
              // 清空表单
              this.textValue = "";
              this.uploadedImages = [];
              // 返回上一页
              uni.navigateBack();
            },
          });
        } else {
          // 提交失败，显示错误信息
          const errorMsg =
            res.data?.message || res.message || "提交失败，请重试";
          uni.showModal({
            title: "提交失败",
            content: errorMsg,
            showCancel: false,
            confirmText: "重试",
          });
        }
      });
    },
    //轮播图指示器
    swiperChange(event) {
      this.currentSwiper = event.detail.current;
    },
    // 购物车列表
    carList() {
      uni.switchTab({
        url: "/pages/tabBar/cart/cart",
      });
    },
    // 分享
    share() {
      this.shareClass = "show";
    },
    hideShare() {
      this.shareClass = "hide";
      setTimeout(() => {
        this.shareClass = "none";
      }, 150);
    },
    //返回上一页
    back() {
      uni.navigateBack();
    },

    // 选择图片
    chooseImages() {
      if (this.isUploading) {
        uni.showToast({
          title: "正在上传，请稍候",
          icon: "none",
        });
        return;
      }

      const remainingCount = 5 - this.uploadedImages.length;

      uni.chooseImage({
        count: remainingCount,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          this.uploadImages(res.tempFilePaths);
        },
        fail: (err) => {
          console.error("选择图片失败:", err);
          uni.showToast({
            title: "选择图片失败",
            icon: "none",
          });
        },
      });
    },

    // 上传图片
    uploadImages(tempFilePaths) {
      if (tempFilePaths.length === 0) return;

      this.isUploading = true;
      uni.showLoading({
        title: "上传中...",
      });

      // 逐个上传图片
      const uploadPromises = tempFilePaths.map((filePath) => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: BASE_URL + "/api/file/fileUpload",
            filePath: filePath,
            name: "file",
            header: {
              Authorization: uni.getStorageSync("token")
                ? `Bearer ${uni.getStorageSync("token")}`
                : "",
            },
            success: (uploadRes) => {
              try {
                const { data: result } = JSON.parse(uploadRes.data) || {};
                console.log("result+++", result);
                if (result.ok && result.data && result.data.url) {
                  resolve({
                    url: result.data.url,
                    originalname: result.data.originalname || "image",
                    size: result.data.size || 0,
                  });
                } else {
                  reject(new Error(result.message || "上传失败"));
                }
              } catch (error) {
                reject(new Error("解析上传结果失败"));
              }
            },
            fail: (error) => {
              reject(new Error("网络上传失败"));
            },
          });
        });
      });

      Promise.all(uploadPromises)
        .then((results) => {
          this.uploadedImages = [...this.uploadedImages, ...results];
          uni.hideLoading();
          uni.showToast({
            title: `成功上传${results.length}张图片`,
            icon: "success",
          });
        })
        .catch((error) => {
          console.error("上传图片失败:", error);
          uni.hideLoading();
          uni.showToast({
            title: error.message || "上传图片失败",
            icon: "none",
          });
        })
        .finally(() => {
          this.isUploading = false;
        });
    },

    // 删除图片
    deleteImage(index) {
      uni.showModal({
        title: "确认删除",
        content: "确定要删除这张图片吗？",
        success: (res) => {
          if (res.confirm) {
            this.uploadedImages.splice(index, 1);
            uni.showToast({
              title: "删除成功",
              icon: "success",
            });
          }
        },
      });
    },

    // 预览图片
    previewImage(url) {
      const urls = this.uploadedImages.map((img) => img.url);
      uni.previewImage({
        current: url,
        urls: urls,
      });
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f8f8f8;
}

@keyframes showPopup {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

@keyframes hidePopup {
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}

@keyframes showLayer {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-100%);
  }
}

@keyframes hideLayer {
  0% {
    transform: translateY(-100%);
  }

  100% {
    transform: translateY(0);
  }
}

.icon {
  font-size: 26upx;
}

.status {
  width: 100%;
  height: 0;
  position: fixed;
  z-index: 10;
  top: 0;
  /*  #ifdef  APP-PLUS  */
  height: var(--status-bar-height); //覆盖样式
  /*  #endif  */
  background-color: #f1f1f1;
  transition: opacity 0.05s linear;
}

.header {
  width: 100%;

  height: 100upx;
  display: flex;
  align-items: center;
  position: fixed;
  top: 0;
  z-index: 10;
  /*  #ifdef  APP-PLUS  */
  top: var(--status-bar-height);

  /*  #endif  */
  .before,
  .after {
    width: 92%;
    padding: 0 4%;
    height: 100upx;
    display: flex;
    align-items: center;
    position: fixed;
    top: 0;
    /*  #ifdef  APP-PLUS  */
    top: var(--status-bar-height);
    /*  #endif  */
    transition: opacity 0.05s linear;

    .back {
      width: 125upx;
      height: 60upx;
      flex-shrink: 0;

      .icon {
        margin-left: -10%;
        width: 60upx;
        height: 60upx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 42upx;
      }
    }

    .middle {
      width: 100%;
      font-size: 30upx;
      padding-left: 140upx;
    }

    .icon-btn {
      width: 125upx;
      height: 60upx;
      flex-shrink: 0;
      display: flex;

      .icon {
        &:first-child {
          margin-right: 5upx;
        }

        width: 60upx;
        height: 60upx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 42upx;
      }
    }
  }

  .before {
    .back {
      .icon {
        color: #fff;
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 100%;
      }
    }

    .icon-btn {
      .icon {
        color: #fff;
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 100%;
      }
    }
  }

  .after {
    background-color: #f1f1f1;

    .back {
      .icon {
        color: #666;
      }
    }

    .icon-btn {
      .icon {
        color: #666;
      }
    }

    .middle {
      font-size: 32upx;
      height: 90upx;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0 7%;

      view {
        width: calc(100% / 3);
        padding: 0 3%;
        margin: 0 3%;
        display: flex;
        justify-content: center;
        align-items: center;

        &.on {
          margin-bottom: -4upx;
          color: #f47952;
          border-bottom: solid 4upx #f47952;
        }
      }
    }
  }
}

.place {
  background-color: #ffffff;
  height: 100upx;
  /*  #ifdef  APP-PLUS  */
  margin-top: var(--status-bar-height);
  /*  #endif  */
}

.goods-info {
  padding: 20upx 0;

  .title {
    font-size: 24upx;
    padding: 0 20upx;
    color: #333;
    margin-bottom: 20upx;
  }

  .textarea-box {
    margin-top: 30upx;
    background: #fff;
    padding: 20upx;

    textarea {
      height: 800upx;
    }
  }

  .image-upload-section {
    margin-top: 30upx;
    background: #fff;
    padding: 20upx;

    .image-upload-box {
      display: flex;
      flex-wrap: wrap;
      gap: 20upx;

      .uploaded-images {
        display: flex;
        flex-wrap: wrap;
        gap: 20upx;
        width: 100%;

        .image-item {
          position: relative;
          width: 160upx;
          height: 160upx;
          border-radius: 12upx;
          overflow: hidden;
          background: #f5f5f5;

          image {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .delete-btn {
            position: absolute;
            top: 0upx;
            right: 0upx;
            width: 40upx;
            height: 40upx;
            background: #ff4757;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2upx 8upx rgba(0, 0, 0, 0.2);

            .icon {
              color: #fff;
              font-size: 28upx;
              font-weight: bold;
              line-height: 1;
            }
          }
        }
      }

      .upload-btn {
        width: 160upx;
        height: 160upx;
        border: 2upx dashed #ddd;
        border-radius: 12upx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background: #fafafa;

        .icon {
          font-size: 60upx;
          color: #ccc;
          margin-bottom: 10upx;
        }

        .text {
          font-size: 24upx;
          color: #999;
          margin-bottom: 5upx;
        }

        .tip {
          font-size: 20upx;
          color: #ccc;
        }

        &:active {
          background: #f0f0f0;
          border-color: #bbb;
        }
      }
    }
  }
}

.footer {
  position: fixed;
  bottom: 0upx;
  width: 92%;
  padding: 0 4%;
  height: 99upx;
  border-top: solid 1upx #eee;
  background-color: #fff;
  z-index: 2;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .icons {
    display: flex;
    height: 80upx;
    margin-left: 0;

    .box {
      width: 80upx;
      height: 80upx;
      display: flex;
      justify-content: center;
      flex-wrap: wrap;

      .icon {
        font-size: 40upx;
        color: #828282;
      }

      .text {
        display: flex;
        justify-content: center;
        width: 100%;
        font-size: 22upx;
        color: #666;
      }
    }

    .uni-button-box {
      padding: 0;
      background-color: #fff;
      border: 0;

      &::after {
        border: 0;
      }

      .icon.fenxiang {
        // width: 24px;
        height: 20px;
        position: relative;

        &::before {
          position: relative;
          top: -16px;
          left: 0px;
          height: 24px;
          width: 24px;
        }
      }

      .text {
        height: 24px;
        line-height: 24px;
      }
    }
  }

  .btn {
    height: 80upx;
    border-radius: 40upx;
    overflow: hidden;
    display: flex;
    margin-right: -2%;

    .joinCart,
    .buy {
      height: 80upx;
      padding: 0 40upx;
      color: #fff;
      display: flex;
      align-items: center;
      font-size: 28upx;
    }

    .joinCart {
      background-color: #f0b46c;
    }

    .buy {
      background-color: #f06c7a;
    }
  }
}

.share {
  display: none;

  &.show {
    display: block;

    .mask {
      animation: showPopup 0.15s linear both;
    }

    .layer {
      animation: showLayer 0.15s linear both;
    }
  }

  &.hide {
    display: block;

    .mask {
      animation: hidePopup 0.15s linear both;
    }

    .layer {
      animation: hideLayer 0.15s linear both;
    }
  }

  &.none {
    display: none;
  }

  .mask {
    background-color: rgba(0, 0, 0, 0.5);
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    z-index: 11;
  }

  .layer {
    width: 92%;
    position: fixed;
    z-index: 12;
    padding: 0 4%;
    top: 100%;
    background-color: rgba(255, 255, 255, 0.9);

    .list {
      width: 100%;
      display: flex;
      padding: 10upx 0 30upx 0;

      .box {
        width: 25%;
        display: flex;
        justify-content: center;
        flex-wrap: wrap;

        image {
          width: 13.8vw;
          height: 13.8vw;
        }

        .title {
          margin-top: 10upx;
          display: flex;
          justify-content: center;
          width: 100%;
          font-size: 26upx;
        }
      }
    }

    .btn {
      width: 100%;
      height: 100upx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28upx;
      border-top: solid 1upx #666666;
    }

    .h1 {
      width: 100%;
      height: 80upx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 34upx;
    }
  }
}
</style>
